<template>
  <!-- 外部渠道出库管理 -->
  <customContainer ref="configRef" :config="config" />
  <div>
    <el-dialog v-model="open" title="签出">
      <el-form
        ref="checkoutForms"
        :model="checkoutForm" 
        :rules="checkoutRules"
        label-width="100px"
        inline
      >
        <el-form-item label="服务商" prop="providerServiceCode">
          <el-select
            v-model="checkoutForm.providerServiceCode"
            filterable
            clearable
            style="width: 200px;"
          >
            <el-option
              v-for="dict in dicts[DictDirection.服务商]"
              :key="dict.providerServiceCode"
              :label="dict.serviceSimpleName"
              :value="dict.providerServiceCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务渠道" prop="serviceChannelCode">
          <el-select
            v-model="checkoutForm.serviceChannelCode"
            clearable
            filterable
            style="width: 200px;"
          >
            <el-option
              v-for="dict in dicts[DictDirection.服务渠道]"
              :key="dict.serviceChannelCode"
              :label="dict.channelChName"
              :value="dict.serviceChannelCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提单号" prop="ladingNo">
          <el-input v-model.trim="checkoutForm.ladingNo" style="width: 200px;"></el-input>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="handleCheckOutSubmit">确定</el-button>
        <el-button type="info" @click="checkoutCancel">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="open2" title="数据详情" append-to-bod>
      <el-form
        v-loading="loading"
        :model="form"
        inline
        label-width="130px"
      >
        <el-form-item label="系统订单号：" class="title">
          <span class="context">{{ form.orderNo }}</span>
        </el-form-item>
        <el-form-item label="拆单订单号：" class="title">
          <span class="context">{{ form.parentOrderNo }}</span>
        </el-form-item>
        <el-form-item label="客户订单号：" class="title">
          <span class="context">{{ form.waybillNo }}</span>
        </el-form-item>
        <el-form-item label="客户名称：" class="title">
          <span class="context">{{ form.customerName }}</span>
        </el-form-item>
        <el-form-item label="分区代码：" class="title">
          <span class="context">{{ form.partitionCode }}</span>
        </el-form-item>
        <el-form-item label="业务员：" class="title">
          <span class="context">{{ form.businessManager }}</span>
        </el-form-item>
        <el-form-item label="销售产品：" class="title">
          <span class="context">{{ form.marketProducts }}</span>
        </el-form-item>
        <el-form-item label="报价类型：" class="title">
          <span class="context">{{ form.quotationType }}</span>
        </el-form-item>
        <el-form-item label="自定义价格：" class="title">
          <span class="context">{{ form.customPrice }}</span>
        </el-form-item>
        <el-form-item label="收货材积系数：" class="title">
          <span class="context">{{ form.receivingWoodCoefficient }}</span>
        </el-form-item>
        <el-form-item label="收货体积系数：" class="title">
          <span class="context">{{ form.receivingVolumeCoefficient }}</span>
        </el-form-item>
        <el-form-item label="收货总实重：" class="title">
          <span class="context">{{ form.receivingTotalWeight }}</span>
        </el-form-item>
        <el-form-item label="收货总材积：" class="title">
          <span class="context">{{ form.receivingTotalWood }}</span>
        </el-form-item>
        <el-form-item label="收货计费重：" class="title">
          <span class="context">{{ form.receivingTotalCharging }}</span>
        </el-form-item>
        <el-form-item label="收货总件数：" class="title">
          <span class="context">{{ form.receivingTotal }}</span>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button type="info" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, getCurrentInstance } from 'vue'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { checkoutList, checkoutDetails, outCheckout, revokeOut, submittedOverseasWarehouse, domesticCustomsDeclaration } from '@/api/expressManager/external'
import userStore from '@/store/modules/user'

const user = userStore()
const dicts = useDicts()
dicts.setDicts(DictDirection.产品)
dicts.setDicts(DictDirection.包裹状态)
dicts.setDicts(DictDirection.服务商)
dicts.setDicts(DictDirection.服务渠道)
dicts.setDicts(DictDirection.国家)
dicts.setDicts(DictDirection.货物类型)
const userName = user.user.nickName
const configRef = ref(undefined)
const open = ref(false)
const open2 = ref(false)
const multiple = ref(true),
  single = ref(true)
const queryParams = ref({
  pageSize: 10,
  pageNum: 1,
  transportType: 9,
  waybillNo: undefined,
  ladingNo: undefined,
  orderNo: undefined,
  agent: undefined,
  voyageNo: undefined,
  transportName: undefined,
  caseNo: undefined,
  splittingStatus: undefined,   
})
const loading = ref(false)
const { proxy } = getCurrentInstance() as any
const checkoutRules = {
  providerServiceCode: [{ required: true, message: '必填', trigger: 'change' }],
  serviceChannelCode: [{ required: true, message: '必填', trigger: 'change' }],
  ladingNo: [{ required: true, message: '必填', trigger: 'blur' }],
}
const checkoutForm = ref({
  providerServiceCode: '',
  serviceChannelCode: '',
  ladingNo: '',
})
const checkoutForms = ref(undefined)
// 签出
const handleAddTotalOrder = () => {
  open.value = true
}
const handleCheckOutSubmit = () => {
  const data = {
    executorName: userName,
    orderNoList: orderNos.value,
    idList: idss.value,
    providerServiceCode: checkoutForm.value.providerServiceCode,
    serviceChannelCode: checkoutForm.value.serviceChannelCode,
    ladingNo: checkoutForm.value.ladingNo,
    transportType: '9',
    serviceSimpleName: 'AINIEN',
  }
  outCheckout(data).then(res => {
    if (res.code == 200) {
      ElMessage.success('签出成功')
      open.value = false
      proxy.$refs.checkoutForms.resetFields()
      configRef.value.getList()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
// 撤销
const handleRevoke = () => {
  const data = {
    orderNoList: orderNos.value,
  }
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] !== '4') {
    ElMessageBox.confirm('敏感操作！是否继续？', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      revokeOut(data).then(res => {
        if (res.code == 200) {
          ElMessage.success('撤销成功')
          configRef.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    })
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
const checkoutCancel = () => {
  open.value = false
  proxy.$refs.checkoutForms.resetFields()
}
// 查看详情
const form = ref({
  orderNo: '',
  parentOrderNo: '',
  waybillNo: '',
  customerName: '',
  partitionCode: '',
  businessManager: '',
  marketProducts: '',
  quotationType: '',
  customPrice: '',
  receivingWoodCoefficient: '',
  receivingVolumeCoefficient: '',
  receivingTotalWeight: '',
  receivingTotalWood: '',
  receivingTotalCharging: '',
  receivingTotal: '',
})
const toMainInfo = (row: { [key: string]: any }) => {
  open2.value = true
  loading.value = true
  rowIds.value = row.id
  getList2()
}
const cancel = () => {
  open2.value = false
}
// 国内报关
const handleDeclaration = () => {
  const data = {
    orderNoList: orderNos.value,
  }
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] !== '4') {
    ElMessageBox.confirm('敏感操作！是否继续？', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      domesticCustomsDeclaration(data).then(res => {
        if (res.code == 200) {
          ElMessage.success('国内报关成功')
          configRef.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    })
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
// 国内查验 
const handleInspection = () => {
 
}
// 已提交海外仓
const handleOverseas = () => {
  const data = {
    orderNoList: orderNos.value,
  }
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] !== '4') {
    ElMessageBox.confirm('敏感操作！是否继续？', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      submittedOverseasWarehouse(data).then(res => {
        if (res.code == 200) {
          ElMessage.success('提交海外仓成功')
          configRef.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    })
  } else {
    ElMessageBox.alert('只有签出的才能操作')
  }
}
const orderNos = ref([])
const idss = ref([])
const otherDisabled = ref(true)
const handleTableSelect = (rows: { [key: string]: any }[]) => {
  multiple.value = !rows.length
  single.value = rows.length != 1
  orderNos.value = rows.map((item) => item.orderNo)
  statuss.value = rows.map((item) => item.status)
  idss.value = rows.map((item) => item.id)
  const result2 = rows.every(c => c.splittingStatus !== '2')
  if (result2 && rows.length > 0) {
    otherDisabled.value = false
  } else {
    otherDisabled.value = true
  }
}
const rowIds = ref(null)
const statuss = ref([])
const getList2 = () => {
  const id = rowIds.value
  checkoutDetails(id).then(res => {
    if (res.code == 200) {
      form.value = res.data
      loading.value = false
    }
  }).catch(() => {
    loading.value = false
  })
}
const config = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '客户订单号',
            prop: 'waybillNo',
            option: {
              type: 'textarea',
            },
          },
          {
            label: '系统订单号',
            prop: 'orderNo',
          },
          {
            label: '提单号',
            prop: 'ladingNo',
            // option: {
            //   type: 'textarea',
            // },
          },
          {
            type: 'select',
            label: '服务商',
            prop: 'agent',
            option: {
              dictInfo: { dict: DictDirection.是否禁用字典 },
            },
          },

          {
            label: '航次/航班号',
            prop: 'voyageNo',
          },
          {
            label: '船公司',
            prop: 'transportName',
          },
          {
            label: '箱号',
            prop: 'caseNo',
          },

          {
            type: 'select',
            label: '订单状态',
            prop: 'splittingStatus',
            option: {
              dictInfo: { dict: DictDirection.包裹状态 },
            },
          },
        ],
        queryParams: queryParams.value,
        formOption: {},
      },
      btns: [
        {
          title: '签出',
          type: 'primary',
          onClick: handleAddTotalOrder,
          disabled: multiple.value,
        },
        {
          title: '撤销',
          onClick: handleRevoke,
          type: 'primary',
          disabled: otherDisabled.value,
        },
        {
          title: '国内报关',
          onClick: handleDeclaration,
          type: 'primary',
          disabled: otherDisabled.value,
        },
        {
          title: '国内查验',
          onClick: handleInspection,
          type: 'primary',
          disabled: otherDisabled.value,
        },
        {
          title: '国内已放行',
          onClick() {
            console.log(config)
          },
          type: 'primary',
          disabled: otherDisabled.value,
        },
        {
          title: '已到港',
          onClick() {
            console.log(config)
          },
          type: 'primary',
          disabled: otherDisabled.value,
        },
        {
          title: '国外清关',
          onClick() {
            console.log(config)
          },
          type: 'primary',
          disabled: otherDisabled.value,
        },
        {
          title: '国外查验',
          onClick() {
            console.log(config)
          },
          type: 'primary',
          disabled: otherDisabled.value,
        },

        {
          title: '国外清关已放行',
          onClick() {
            console.log(config)
          },
          type: 'primary',
          disabled: otherDisabled.value,
        },
        {
          title: '已提交UPS',
          onClick() {
            console.log(config)
          },
          type: 'success',
          disabled: otherDisabled.value,
        },
        {
          title: '已提交海外仓',
          onClick: handleOverseas,
          type: 'primary',
          disabled: otherDisabled.value,
        },
      ],
      table: {

        columns: [
          { type: 'selection', width: '55', fixed: 'left' },
          {
            label: '客户单号',
            prop: 'waybillNo',
            align: 'center',
            fixed: 'left',
            width: '160',
            // formatter(row) {
            // 	return row.clientId;
            // },
            // autoFormatter: {
            // 	dict: DictDirection.是否禁用字典,
            // 	rowKey: '1',
            // },
          },
          { label: '主转单号', align: 'center', prop: 'mainTransferOrderNo', fixed: 'left', width: '160' },
          { label: '子转单号', align: 'center', prop: 'transferOrderNo', width: '160' },
          { label: '客户名称', align: 'center', prop: 'customerName' },
          { label: '销售产品',
            align: 'center',
            prop: 'marketProducts',
            autoFormatter: {
              dict: DictDirection.产品,
              rowKey: 'marketProducts',
            } },
          { label: '总实重', align: 'center', prop: 'receivingTotalWeight' },

          { label: '材积重', align: 'center', prop: 'receivingTotalWood' },
          { label: '计费重', align: 'center', prop: 'receivingTotalCharging' },
          { label: '件数', align: 'center', prop: 'receivingTotal' },
          { label: '出货总实重', align: 'center', prop: 'shipmentTotalWeight' },
          { label: '出货材积重', align: 'center', prop: 'shipmentTotalWood' },

          { label: '出货件数', align: 'center', prop: 'shipmentWoodCount' },
          { label: '订单状态',
            align: 'center',
            prop: 'splittingStatus',
            autoFormatter: {
              dict: DictDirection.包裹状态,
              rowKey: 'splittingStatus',
            }, 
          },
          { label: '收货站点', align: 'center', prop: 'receivingSite' },
          { label: '创建日期', align: 'center', prop: 'orderTime' },
          { label: '邮编', align: 'center', prop: 'consigneePostcode' },

          { label: '国家',
            align: 'center',
            prop: 'consigneeCountry',
            autoFormatter: {
              dict: DictDirection.国家,
              rowKey: 'consigneeCountry',
            }, 
          },
          { label: '打印标签次数', align: 'center', prop: 'printTagCount' },
          { label: '标签号', align: 'center', prop: 'tagNumber' },
          { label: '货物类型',
            align: 'center',
            prop: 'goodsType',
            autoFormatter: {
              dict: DictDirection.包裹类型,
              rowKey: 'goodsType',
            } },
          // { :label:queryParams.transportType == 2 ? '预计起飞日' : '预计开船日', prop: 'expectedSailingDate' },
          { label: '业务员', align: 'center', prop: 'businessManager' },

          { label: '制单人', align: 'center', prop: 'maker' },
          { label: '制单日期', align: 'center', prop: 'makerDate' },
          { label: '报关件', align: 'center', prop: 'customsDeclaration' },
          { label: '备注', align: 'center', prop: 'remarks' },
          { label: '系统订单号', align: 'center', prop: 'orderNo' },

          {
            label: '操作',
            align: 'center',
            width: '160',
            fixed: 'right',
            render(h, params) {
              const buttons = [
                {
                  title: '查看详情',
                  clickFun: toMainInfo,
                }]
              return buttons.map((el) => h(
                ElButton,
                {
                  text: true,
                  type: 'primary',
                  onClick: () => {
                    el.clickFun(params.row)
                  },
                },
                {
                  default: () => el.title,
                },
              ))
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleTableSelect(rows)
          },
        },
      },
      api: checkoutList,
      customKey: 'express/NoMainBusiness/externalChannels/externalManagement',
    }
  },

  set(val) {
    return val
  },
})
</script>
<style lang="less" scoped>
/deep/.is-guttered {
  padding: 5px;
}
.title /deep/ .el-form-item__label {
  font-weight: 700;
  font-size: 1em;
}
.title {
  .context {
    width: 200px;
    display: inline-block;
  }
}
</style>
